package com.google.adwords.samples.disapproved;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * Utility methods for getting config
 * @author AlecMGo@gmail.com (Alec Go)
 * 
 */
public class Util {
  
  private static final String CONFIG_FILE = "adwords.properties";
  
  /**
   * Returns a config object based on the CONFIG_FILE
   * @return application configuration
   * @throws AppException
   */
  public static Config getConfig() throws AppException {
    Properties apiProperties = new Properties();
    try {
      FileInputStream in = new FileInputStream(CONFIG_FILE);
      apiProperties.load(in);
      in.close();
    } catch(FileNotFoundException e) {
      throw new AppException(CONFIG_FILE + " not found.");
    } catch(IOException e) {
      throw new AppException(CONFIG_FILE + " not found.");
    }
    
    String email = apiProperties.getProperty("email");
    if(email == null || email.equals("")) {
      throw new AppException("Email must be specified in " + CONFIG_FILE);
    }
    
    String password = apiProperties.getProperty("password");
    if(password == null || password.equals("")) {
      throw new AppException("Password must be specified in " + CONFIG_FILE);
    }
    
    String developerToken = apiProperties.getProperty("developerToken");
    if(developerToken == null || developerToken.equals("")) {
      throw new AppException("developerToken must be specified in " + CONFIG_FILE);
    }
    
    String applicationToken = apiProperties.getProperty("applicationToken");
    if(applicationToken == null || applicationToken.equals("")) {
      throw new AppException("applicationToken must be specified in " + CONFIG_FILE);
    }
    
    String useragent = apiProperties.getProperty("useragent");
    if(useragent == null || useragent.equals("")) {
      throw new AppException("useragent must be specified in " + CONFIG_FILE);
    }
    
    String loginInterface = apiProperties.getProperty("loginInterface");
    if(loginInterface == null || loginInterface.equals("")) {
      throw new AppException("loginInterface must be specified in " + CONFIG_FILE);
    }
    
    String version = apiProperties.getProperty("version");
    if(version == null || version.equals("")) {
      throw new AppException("version must be specified in " + CONFIG_FILE);
    }
    
    return new Config(email, password, applicationToken, developerToken,
        useragent, loginInterface, version);    
  }
}
